/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;
import FileManager.FileTransfer_SERVER;
import FileManager.folderTree;
import Message.Message;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;


/**
 *
 * @author DucThien
 */
public class GUI_Main extends javax.swing.JFrame {

    public static ArrayList<Socket> lstClientSocket;		
    public static ServerSocket server ;
    /// view desktop
    private static JDesktopPane desktop = new JDesktopPane();    
    private static JInternalFrame interFrame = new JInternalFrame("Client Screen",
                                                            true, true, true);
    private static JPanel cPanel = new JPanel();    
    private static JFrame frame = new JFrame();
    private static int  catchPicture = 1;
    
    private static FileTransfer_SERVER fileManager = new FileTransfer_SERVER();
     
    /**
     * Creates new form GUI_Main
     */
    public GUI_Main() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jButton9 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jPanel4 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Lan Support System");
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(164, 180, 255));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED, new java.awt.Color(0, 0, 255), new java.awt.Color(0, 0, 255), new java.awt.Color(0, 0, 255), new java.awt.Color(0, 0, 255)), "Client Manager", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Cambria", 3, 14), new java.awt.Color(0, 0, 204))); // NOI18N
        jPanel2.setOpaque(false);
        jPanel2.setLayout(new java.awt.GridLayout(1, 0, 10, 0));

        jButton1.setBackground(new java.awt.Color(51, 0, 204));
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/chat.png"))); // NOI18N
        jButton1.setToolTipText("Chatting");
        jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jPanel2.add(jButton1);

        jButton2.setBackground(new java.awt.Color(51, 0, 204));
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/email_send.png"))); // NOI18N
        jButton2.setToolTipText("Send Message");
        jButton2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);

        jButton3.setBackground(new java.awt.Color(51, 0, 204));
        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/desktop.png"))); // NOI18N
        jButton3.setToolTipText("Observe Desktop Client");
        jButton3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton3);

        jButton4.setBackground(new java.awt.Color(51, 0, 204));
        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/microsoft_remote_desktop_connection.png"))); // NOI18N
        jButton4.setToolTipText("Remote Desktop");
        jButton4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton4);

        jButton5.setBackground(new java.awt.Color(51, 0, 204));
        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/print.png"))); // NOI18N
        jButton5.setToolTipText("Print Desktop Client");
        jButton5.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jPanel2.add(jButton5);

        jButton6.setBackground(new java.awt.Color(51, 0, 204));
        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/file_manager.png"))); // NOI18N
        jButton6.setToolTipText("File Manager");
        jButton6.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton6);

        jButton7.setBackground(new java.awt.Color(51, 0, 204));
        jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/exec.png"))); // NOI18N
        jButton7.setToolTipText("Execute Command Shell");
        jButton7.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jPanel2.add(jButton7);

        jButton8.setBackground(new java.awt.Color(51, 0, 204));
        jButton8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/gnome_view_refresh.png"))); // NOI18N
        jButton8.setToolTipText("Refresh List Client");
        jButton8.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jPanel2.add(jButton8);

        jButton9.setBackground(new java.awt.Color(51, 0, 204));
        jButton9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/shutdown(1).png"))); // NOI18N
        jButton9.setToolTipText("Disconnect and Close Programe");
        jButton9.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton9);

        jPanel3.setOpaque(false);

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jList1.setName("jlist_client"); // NOI18N
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(258, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(38, 38, 38))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 544, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 813, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 309, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 833, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 501, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public static void Sẹtpanel(){
        
    }
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        System.out.println("Click Remote");
        Socket theclient = lstClientSocket.get(0);
        
       try {
            SendRequestViewDesktop(theclient);
            
            drawGUI();

        /// nhan move tu cac cai khac
        } catch (IOException ex) {
            Logger.getLogger(ReciveClient.class.getName()).log(Level.SEVERE, null, ex);
        }

          
        
        
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
        // TODO add your handling code here:
        System.out.println("Click item!!!!");
    }//GEN-LAST:event_jList1ValueChanged

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        
        JLabel lba = new JLabel("AAAAAA");
        JButton btnClient = new JButton("Client");
        
       // jPanel4.setLayout(new FlowLayout());
        jPanel4.add(btnClient);      
        jPanel4.validate();
        this.validate();
        this.repaint();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jButton9ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        /// view desktop
        
        System.out.println("Click View Desktop client.");
        Socket theclient = lstClientSocket.get(0);        
       try {
            SendRequestViewDesktopNoControl(theclient);            
            drawGUI();

        /// nhan move tu cac cai khac
        } catch (IOException ex) {
            Logger.getLogger(ReciveClient.class.getName()).log(Level.SEVERE, null, ex);
        }
       
       
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        try {
            // TODO add your handling code here:
            Socket client = lstClientSocket.get(0);
            Object obj = new String("Server File!!!");
            Message mssend = new Message(6,1,obj);
            SendMessage(client, mssend);
        } catch (IOException ex) {
            Logger.getLogger(GUI_Main.class.getName()).log(Level.SEVERE, null, ex);
        }       
    }//GEN-LAST:event_jButton6ActionPerformed

    /**
     * @param args the command line arguments
     */
    
       ///function
   
    
     public static void SendMessage(Socket theclient , Message mssend ) throws IOException{ 
	    ObjectOutputStream out = new ObjectOutputStream(theclient.getOutputStream());
            System.out.println("Send Request File Manager !!! ");         
            out.writeObject(mssend);         
        }
     
    
    
    public static void SendRequestViewDesktop(Socket theclient) throws IOException{ 
	    ObjectOutputStream out = new ObjectOutputStream(theclient.getOutputStream());
            System.out.println("Send Request view desktop ");
            Object obj = new String("Server!!!");
            Message mssend = new Message(5,1,obj);
            out.writeObject(mssend);
            drawGUIView();
            
        }
    
    public static void SendRequestViewDesktopNoControl(Socket theclient) throws IOException{ 
            ObjectOutputStream out = new ObjectOutputStream(theclient.getOutputStream());
            System.out.println("Send Request view desktop no control ");
            Object obj = new String("Server!!!");
            Message mssend = new Message(4,1,obj);
            out.writeObject(mssend);
            drawGUIView();
            
        }
    
    
    
    
    
    public static void StartMain() throws IOException{
        
        lstClientSocket = new ArrayList<Socket>();
        server = new ServerSocket(3211);

        do
        {	//System.out.print("a");
            try{
                Listen();
            }catch(Exception e)
            {
                break;
            }
                //System.out.print("end a");
        }
        while (true);
                
    }
        public  void ShowClientInJList(Socket theclient){
            
            
            JLabel lba = new JLabel("AAAAAA");
            JButton btnClient = new JButton("Client");
            System.out.println("Zo..........");
           // jPanel4.setLayout(new FlowLayout());
            jPanel4.add(btnClient);      
            jPanel4.validate();
            this.validate();
            this.repaint();
            System.out.println("Zo..........end");

            
            //String ipClient = theclient.getLocalAddress().toString();
            
            /*JButton btnClient = new JButton("Client");            
            JLabel lb = new JLabel("COngtt");
            
          
            jPanel4.add(lb);
            jPanel4.revalidate();
            jPanel4.repaint();
                     
            this.revalidate();
            this.repaint();
          */
            
            
            /* DefaultListModel model = new DefaultListModel();
            jList1 = new JList(model);

            // Initialize the list with items
            String[] items = {"A", "B", "C", "D"};
            for (int i=0; i<items.length; i++) {
                model.add(i, items[i]);
            }

            // Append an item
            int pos = list.getModel().getSize();
            model.add(pos, "E");

            // Insert an item at the beginning
            pos = 0;
            model.add(pos, "a");*/

        }
     
      public static  void Listen() throws InterruptedException
      {
            try {			

                    System.out.println("Waiting for a Client connect...");

                    Socket ss = server.accept(); //synchronous			
                    lstClientSocket.add(ss);
                    GUI_Main m = new GUI_Main();
                    m.ShowClientInJList(ss);
                    System.out.println("count accept " + lstClientSocket.size() +" name: "+  ss.toString());
                    System.out.println("IP: " + ss.getRemoteSocketAddress());
                    HandClient(ss);// nhan data tu client.


            }
            catch (IOException e) {

                    System.out.println("Loi khi listen client."+ e.toString());

            }

    }
      
     
     
    
    public static ImageIcon createImageIcon(String path) {
          java.net.URL imgURL = GUI_Main.class.getResource(path);
          if (imgURL != null) {
              return new ImageIcon(imgURL);
          } else {
              System.err.println("Couldn't find file: " + path);
              return null;
          }
      }
    
    public static void SaveImage(ImageIcon imagesour , String path){
         /// writer image
        
        try{
            
            Image img = imagesour.getImage();//TYPE_BYTE_ARGB
               //BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_BYTE_ARGB);
            BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bi.createGraphics();
            // Draw img into bi so we can write it to file.
            
            g2.drawImage(img, 0, 0, null);
       
            g2.dispose();
            
            try {
                // Now bi contains the img.
                // Note: img may have transparent pixels in it; if so, okay.
                // If not and you can use TYPE_INT_RGB you will get better
                // performance with it in the jvm.
                ImageIO.write(bi, "jpg", new File(path));

                //BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(nul l), BufferedImage.TYPE_BYTE_ARGB );
            } catch (IOException ex) {
                System.out.println("loi khi write image: "+ex.toString());
                Logger.getLogger(GUI_Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }catch(Exception ex){
            System.out.println("Loi wite: " + ex.toString());
                    
        }

        
    }
    
    public static void HandClient(Socket ss)
	{
		try
		{						
                    ReciveClient rc = new ReciveClient(ss);		
                    
		}
		catch(Exception e)
		{
                    System.out.println("Error in function HandClient!");
		}                
               
		
		
	}
        
        public static void HandMessage(Message ms , Socket socket){
            
            int type;
            System.out.println("zo ham hand messagee");
            type = ms.GetType();
            switch(type){
                case 1: // chat
                    HandChat(ms);
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    HandRemote(ms , socket);
                    break;
                    
                case 6:
                    HandFile(ms , socket);
                    break;
                case 7:
                    break;
                case 8:
                    break;
                case 9:
                    break;                    
            }            
        }        
        public static void  HandChat(Message ms){
            System.out.println("ham chat: ");
            String str = ms.GetData().toString();
            System.out.println("Client: " + str);
        }  
        
        public static void HandFile(Message ms , Socket socket){
            int option = ms.GetOption();
            switch(option){
                case 1:
                    GUI_FileManager GUI_FileManage = new GUI_FileManager((Vector<folderTree>)ms.GetData(), socket);
                    GUI_FileManage.setVisible(true); 
                    break;
                case 2:
                    break;
            }
            
        }        
        public static void XL_Rectangle(Message ms , Socket socket , int type){
           
           System.out.println("XL_ REC========================================================================================"); 
           Rectangle clientScreenDim = null;            
           clientScreenDim =(Rectangle) ms.GetData();
           
           if(type == 1){
               System.out.println("server: co zo ham control");
                new ClientCommandsSender(socket,cPanel,clientScreenDim);
           }
          
        
        }
        
        public static void HandRemote(Message ms , Socket socket){
            int option = ms.GetOption();            
            switch(option){                
                case 1:                   
                    break;
                case 2:
                    XL_NhanHinhView(ms);
                    break;
                case 3:
                     XL_Rectangle(ms , socket  , 1); //1  control
                    break;
                case 4:
                    XL_Rectangle(ms , socket  , 0);// 0 co control
                default:
                    break;
            }
            
        }
        
        // view déktop
        public static void drawGUI(){
          
            
            JButton btnPicture = new JButton("Picture draw"); 
           // btnPicture.addActionListener();
            JPanel pFunction  = new JPanel();
            pFunction.setPreferredSize(new Dimension(500,35));
            pFunction.setBackground(Color.WHITE);
            pFunction.add(btnPicture);
            
            btnPicture.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
                    Global.CatchPic = true;
                    /// file chosesave
                  /*  JFileChooser filePicSave = new JFileChooser("Save Image as");                
                     int returnVal = filePicSave.showSaveDialog(frame);
                     if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = filePicSave.getSelectedFile();                    
                        System.out.println("===================================================save: " + file.getAbsolutePath());

                    } else {
                        //System.out.println("Open command cancelled by user." );
                    }

                    */
                    ///
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });
          
            frame.add(pFunction, BorderLayout.PAGE_START);
            
            frame.add(desktop,BorderLayout.CENTER);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Show the frame in a maximized state
            frame.setExtendedState(frame.getExtendedState()|JFrame.MAXIMIZED_BOTH);
           
         
            
            //
            
            frame.setVisible(true);
    }
        
         public static void drawGUIView(){
             
                        
            interFrame.setLayout(new BorderLayout());
            interFrame.getContentPane().add(cPanel,BorderLayout.CENTER);
            interFrame.setSize(100,100);
            interFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           
             //  frame.setLayout(new FlowLayout());
           /* JButton btnPicture = new JButton("Picture");
            
            JPanel pFunction  = new JPanel();
            pFunction.setPreferredSize(new Dimension(500,50));
            pFunction.setBackground(Color.red);
            pFunction.add(btnPicture);
            //frame.add(pFunction);
            desktop.add(pFunction);
            */
                     
            desktop.add(interFrame);
            try {
                //Initially show the internal frame maximized
                interFrame.setMaximum(true);
            } catch (PropertyVetoException ex) {
                ex.printStackTrace();
            }
            //this allows to handle KeyListener events
            cPanel.setFocusable(true);
            interFrame.setVisible(true);
     }
        
        public static void XL_NhanHinhView(Message ms){
            
            System.out.println("zo ham hien thi hinh");
            catchPicture = catchPicture+1;
           // String str = (String)ms.GetData();
           // System.out.println("data: " + str);
           
            /*System.out.println("Nhan hinh.");
            
            JFrame frame = new JFrame();
             frame = new JFrame("QUẢN LÝ HỌC SINH");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);*/
             
            ImageIcon imageIcon = new ImageIcon();
            imageIcon = (ImageIcon)ms.GetData();
            final ImageIcon ImgFinal = imageIcon;
         
            
             if(Global.CatchPic == true){
                 
                 /// file chosesave
                 try{
                     
                     JFrame framePic = new JFrame("Save Picture from Client.");
                     
                     JPanel ppic = new JPanel(new BorderLayout());
                     JLabel lb = new JLabel(imageIcon);
                     JButton btnSave = new JButton("Save Pic");
                     ppic.add(btnSave, BorderLayout.PAGE_START);
                     ppic.add(lb,BorderLayout.CENTER);
                     framePic.setDefaultCloseOperation(HIDE_ON_CLOSE);
                     framePic.add(ppic);
                     //framePic.setSize(800,800);
                     framePic.setExtendedState(frame.getExtendedState()|JFrame.MAXIMIZED_BOTH);
                     framePic.setVisible(true);
                     
                     btnSave.addActionListener(new ActionListener() {

                         @Override
                         public  void actionPerformed(ActionEvent e) {
                             
                            ///
                              JFileChooser filePicSave = new JFileChooser("Save Image as");                
                                int returnVal = filePicSave.showSaveDialog(frame);
                                if (returnVal == JFileChooser.APPROVE_OPTION) {
                                   File file = filePicSave.getSelectedFile();                    
                                   String location = file.getAbsolutePath();
                                   System.out.println("===================================================save: " + file.getAbsolutePath());
                                    
                                   try{
                                   SaveImage(ImgFinal, location+".jpg");
                                   }catch(Exception ex){
                                       System.out.println("Loi khi save: " + ex.toString());
                                   }

                               } else {
                                   System.out.println("Open command cancelled by user." );
                               }
                     
                             ///
                             throw new UnsupportedOperationException("Not supported yet.");
                         }
                     });
                   /* JFileChooser filePicSave = new JFileChooser("Save Image as");                
                     int returnVal = filePicSave.showSaveDialog(frame);
                     if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = filePicSave.getSelectedFile();                    
                        String location = file.getAbsolutePath();
                        System.out.println("===================================================save: " + file.getAbsolutePath());
                        
                        SaveImage(imageIcon, location+".jpg");
                       
                        
                    } else {
                        System.out.println("Open command cancelled by user." );
                    }
                     */
                     
                 }catch(Exception ex){
                     System.out.println("Loi save pic!!!!!!!!!!!!!!!!!!!!!!!!!!!11");
                 }
                    
                    ///
                 
                  Global.CatchPic = false;
                 //SaveImage(imageIcon, "hinhcxlient_"+catchPicture+".jpg");
             }
             
             
             
             Image image = imageIcon.getImage();
             image = image.getScaledInstance(cPanel.getWidth(),cPanel.getHeight()
                                                        ,Image.SCALE_FAST);
                    
              Graphics graphics = cPanel.getGraphics();
             // graphics.drawImage(image, 0, 0, 100, 100, cPanel);
             graphics.drawImage(image, 0, 0, cPanel.getWidth(),cPanel.getHeight(),cPanel);
               
           
             /*JPanel p = new JPanel();
             JLabel lb = new JLabel(img);
             lb.setSize(800,800);
             
             p.add(lb);
             frame.add(p);
             frame.setSize(800, 800);
             frame.setVisible(true);*/
             
                    
            
        }
          
        public static void HandViewDesktop(Message ms){
            
        }
            
        public static void HandShell(Message ms){
            
        } 
        
    ///end function
    
    public static void CallListen() throws IOException{
         lstClientSocket = new ArrayList<Socket>();
         server = new ServerSocket(3211);
         
         ListenClient listen = new ListenClient();
         
         
         
         
         
        
    }
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUI_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUI_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUI_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUI_Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new GUI_Main().setVisible(true);                   
                    
                    CallListen();
                    
               
                    /*JFrame fram = new JFrame();
                    fram.setSize(100, 100);
                    fram.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    
                    frame.setVisible(true);*/
                    
                    
                    /*
                    try {
                        StartMain();
                    } catch (IOException ex) {
                        Logger.getLogger(GUI_Main.class.getName()).log(Level.SEVERE, null, ex);
                    }*/
                } catch (IOException ex) {
                    Logger.getLogger(GUI_Main.class.getName()).log(Level.SEVERE, null, ex);
                }
              
            }
        });
    }
    
   
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}

class ThaoTacGUI extends GUI_Main{
    
    public void SetPanel(JPanel p , JButton b){
        
        p.add(b);
        
    }
    
}

class ListenClient extends GUI_Main implements Runnable{

   
    public  ListenClient(){  
       
        Thread t = new Thread(this); 
        t.start();         
    }
    @Override
    public void run() {
        
        while(true){
            try {
                Listen();
            } catch (InterruptedException ex) {
                Logger.getLogger(ListenClient.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            try {
                Thread.sleep(400);
            } catch (InterruptedException ex) {
                Logger.getLogger(ListenClient.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }        
       // throw new UnsupportedOperationException("Not supported yet.");
        
    }
    
}